// pages/shoppingcart/shoppingcart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    network: getApp().globalData['network'],
    id: "",
    carts: [],
    paysum: 0,
    selectall: false,
    ppaysum: 0
  },
  getPaySum: function (carts) {
    var sum = 0;
    for (let i = 0, len = carts.length; i < len; i++) {
      if (carts[i].ischecked && carts[i].status == 1) {
        sum += carts[i].goods_num * carts[i].goods_price;
      }
    }
    this.setData({
      paysum: sum
    });
    console.log(this.data.paysum);
    return this.data.paysum;
  },
  //跳转到detail
  todetail: function (event) {
    var index = event.currentTarget.dataset.index;
    console.log(index);
    wx.navigateTo({
      url: "/pages/detail/detail",
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          // console.log(data)
        },
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', index)
      }
    });
  },
  subnum: function (event) {
    var index = event.currentTarget.dataset.index;
    var goods_num = "carts[" + index + "].goods_num";
    var value = this.data.carts[index].goods_num - 1;
    if (value >= 0) {
      this.setData({
        [goods_num]: value
      });
    } else {
      wx.showToast({
        title: "数量不够减",
        icon: "none"
      })
    }
    this.getPaySum(this.data.carts);

  },
  // 给数组设置值要注意。 this.setData{[]是有括号 应该算是地址值吧}
  addnum: function (event) {
    var index = event.currentTarget.dataset.index;
    var goods_num = "carts[" + index + "].goods_num";
    var value = this.data.carts[index].goods_num + 1;
    this.setData({
      [goods_num]: value
    });
    console.log(this.data.carts);
    this.getPaySum(this.data.carts);
  },
  Selected: function (event) {
    var index = event.currentTarget.dataset.index;
    let list = this.data.carts;
    list[index].ischecked = !list[index].ischecked;
    this.setData({
      list
    })
    this.getPaySum(this.data.carts);
  },
  selectAll: function (event) {
    let selall = this.data.selectall;
    let carts = this.data.carts;
    selall = !selall;
    console.error(selall);
    if (selall == true) {
      for (let i = 0, len = carts.length; i < len; i++) {
        let newcheckbox = 'carts[' + i + '].ischecked';
        this.setData({
          [newcheckbox]: true,
          selectall: true
        })
      }
    } else {
      for (let i = 0, len = carts.length; i < len; i++) {
        let newcheckbox = 'carts[' + i + '].ischecked';
        this.setData({
          [newcheckbox]: false,
          selectall: false
        })
      }
    }
    this.getPaySum(this.data.carts);
  },
  queryCart: function (id) {
    var that = this;
    wx.request({
      url: "http://" + that.data.network + "/front/queryCart.php",
      method: "post",
      data: {
        id: id
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (data) {
        console.log(data);
        that.setData({
          id: id,
          carts: data.data
        });
        that.getPaySum(that.data.carts);
        // console.log(that.data.carts);
        // console.log(that.data.id);
      }
    });
  },
  ondel: function (event) {
    var that = this;
    let carts = this.data.carts;
    that.getPaySum(that.data.carts);
    for (let i = 0, len = carts.length; i < len; i++) {
      if (carts[i].ischecked) {
        carts[i].status = -1;
      }
    }
    this.setData({
      carts
    });
    wx.request({
      url: "http://" + that.data.network + "/front/deleteCart.php",
      method: "post",
      data: {
        carts: JSON.stringify(that.data.carts)
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (data) {
        console.log(data);
        wx.showToast({
          title: "删除成功",
          icon: "none",
          duration: 1000
        });
        that.getPaySum(that.data.carts);
      }
    });
    console.log(carts);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var that = this;
    // var id = wx.getStorageSync("id");
    // console.log(this.data.network);

    //this.queryCart(id);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var id = wx.getStorageSync("id");
    this.queryCart(id);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    console.log("onhide");
    var id = wx.getStorageSync("id");
    wx.request({
      url: "http://" + that.data.network + "/front/updateCart.php",
      method: "post",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        user_id: id,
        carts: JSON.stringify(that.data.carts)
      },
      success: function (data) {
        console.log(data);
      }

    });
  },
  //结算 
  paymoney: function (event) {
    var that = this;
    let carts = this.data.carts;
    let ordermoney = that.getPaySum(that.data.carts);
    console.log("ordermoney=" + ordermoney);
    // 创建订单
    wx.request({
      url: "http://" + that.data.network + "/front/createOrder.php",
      method: "post",
      data: {
        carts: JSON.stringify(that.data.carts),
        ordermoney:ordermoney
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (data) {
        console.log(data);
        wx.showToast({
          title: "创建成功",
          icon: "none",
          duration: 1000
        });
        that.getPaySum(that.data.carts);
      }
    });
    wx.setStorageSync({"carts":that.data.carts});
    for(let i=0,len=carts.length;i<len;i++){
      if(carts[i].ischecked){
        carts[i].status = -1;
      }
    }
    that.setData({
      carts,
      ppaysum:ordermoney
    });
    wx.request({
      url:"http://"+that.data.network+"/front/submitCart.php",
      method:"post",
      data:{
        carts:JSON.stringify(that.data.carts)
      },
      header:{
        "Content-Type":"application/x-www-form-urlencoded"
      },
      success: function (data) {
        console.log(data);
        that.getPaySum(that.data.carts);
        wx.navigateTo({
          url:"/pages/order/order", 
        });
      }
    });
    console.log(carts);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})